<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pms:category:add']"
          >新增</el-button
        >
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="categoryList"
      row-key="id"
      :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
    >
      <el-table-column label="名称" align="left" prop="name" width="160" />
      <el-table-column label="图标" align="center" prop="icon">
        <template width="60" slot-scope="scope">
          <img
            style="width: 50px; height: 50px; border: none"
            :src="scope.row.icon"
          />
        </template>
      </el-table-column>
      <el-table-column label="是否删除" align="center" prop="isDelete">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.isDelete"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </template>
      </el-table-column>

      <el-table-column label="是否显示在首页" align="center" prop="showIndex">
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.showIndex"
            :active-value="1"
            :inactive-value="0"
          ></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="属性管理" align="center">
        <template slot-scope="scope">
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-s-operation"
            @click.native="attrKeyMgr(scope.row)"
            >管理</el-button
          >
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pms:category:edit']"
            >修改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-plus"
            @click="handleAdd(scope.row)"
            v-hasPermi="['pms:category:add']"
            >新增</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pms:category:remove']"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改商品类别对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入名称" />
        </el-form-item>
        <el-form-item label="icon" prop="icon">
          <el-upload
            action="#"
            :http-request="requestUpload"
            :show-file-list="false"
            :before-upload="beforeUpload"
          >
            <div class="uploadpic">
              <img v-bind:src="form.icon" title="点击上传" class="img-lg" />
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="是否删除" prop="isDelete">
          <el-input v-model="form.isDelete" placeholder="请输入是否删除" />
        </el-form-item>

        <el-form-item label="父类别" prop="pid">
          <treeselect
            v-model="form.pid"
            :options="categoryOptions"
            :normalizer="normalizer"
            placeholder="请选择父类别"
          />
        </el-form-item>
        <el-form-item label="是否显示在首页" prop="showIndex">
          <el-input
            v-model="form.showIndex"
            placeholder="请输入是否显示在首页"
          />
        </el-form-item>
        <el-form-item label="顺序" prop="sort">
          <el-input v-model="form.sort" placeholder="请输入顺序" />
        </el-form-item>
        <el-form-item label="链接地址" prop="url">
          <el-input v-model="form.url" placeholder="请输入链接地址" />
        </el-form-item>
        <el-form-item label="备注" prop="descript">
          <el-input v-model="form.descript" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="属性管理" :visible.sync="attrKey.visible" width="70%">
      <el-row>
        <el-col :span="24">
          <el-button
            type="success"
            size="mini"
            icon="el-icon-plus"
            @click.native="attrKeyAdd"
            >添加</el-button
          >
        </el-col>
      </el-row>
      <el-table
        :data="attrKey.list"
        element-loading-text="Loading"
        border
        fit
        highlight-current-row
      >
        <el-table-column label="属性名">
          <template slot-scope="scope">
            {{ scope.row.attrName }}
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click.native="attrKeyEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="mini"
              icon="el-icon-edit"
              @click.native="openAttrValDialog(scope.row)"
              >编辑属性值</el-button
            >
            <el-button
              type="danger"
              size="mini"
              icon="el-icon-delete"
              @click.native="attrKeyRemove(scope.row.id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script>
import {
  listCategory,
  getCategory,
  delCategory,
  addCategory,
  updateCategory,
} from "@/api/pms/category";
import { uploadPic } from "@/api/pms/brand";
import {
  listKey,
  getKey,
  delKey,
  addKey,
  updateKey,
  getlistKey,
} from "@/api/pms/key";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";

export default {
  name: "Category",
  components: {
    Treeselect,
  },
  data() {
    return {
      /*---------------属性管理相关参数 start ----------------*/
      attrKey: {
        idCategory: "",
        visible: false,
        list: [],
      },
      /*----------------属性管理相关参数 end ----------------*/
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 商品类别表格数据
      categoryList: [],
      // 商品类别树选项
      categoryOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        modifyBy: null,
        modifyTime: null,
        descript: null,
        icon: null,
        isDelete: null,
        name: null,
        pid: null,
        showIndex: null,
        sort: null,
        url: null,
      },
      //属性查询参数
      keyQueryParams: {
        modifyBy: null,
        modifyTime: null,
        attrName: null,
        idCategory: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /*---------------属性管理相关method start ----------------*/
    attrKeyMgr(data) {
      this.attrKey.visible = true;
      this.attrKey.idCategory = data.id;
      getlistKey({ idCategory: this.attrKey.idCategory }).then((response) => {
        this.attrKey.list = response.attrlist;
      });
    },

    attrKeyAdd() {
      this.$prompt("请输入属性名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
      }).then(({ value }) => {
        if (!value || value === "") {
          this.$message({
            type: "warning",
            message: "属性名不能为空",
          });
        }
        addKey({ attrName: value, idCategory: this.attrKey.idCategory }).then(
          (response) => {
            this.$message({
              type: "success",
              message: "新增属性成功",
            });
            getlistKey({ idCategory: this.attrKey.idCategory }).then(
              (response2) => {
                this.attrKey.list = response2.attrlist;
              }
            );
          }
        );
      }).catch(e=>e);
    },

    attrKeyEdit(item) {
      this.$prompt("请输入属性名", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: item.attrName,
      }).then(({ value }) => {
        if (!value || value === "") {
          this.$message({
            type: "warning",
            message: "属性名不能为空",
          });
        }
        updateKey({id:item.id,attrName:value}).then((response) => {
          item.attrName = value;
          this.$message({
            type: "success",
            message: "编辑成功",
          });
        });
        return;
      }).catch(e=>e) ;
    },
    attrKeyRemove(id) {
      delKey(id).then((response) => {
        this.$message({
          type: "success",
          message: "删除成功",
        });
        getlistKey({ idCategory: this.attrKey.idCategory }).then(
          (response2) => {
            this.attrKey.list = response2.attrlist;
          }
        );
      });
    },
    /*---------------属性管理相关method end ----------------*/
    // 上传预处理
    beforeUpload(file) {},
    // 默认的上传行为
    requestUpload(param) {
      let formData = new FormData();
      formData.append("uploadfile", param.file);
      uploadPic(formData).then((response) => {
        this.form.icon = response.imgUrl;
      });
    },
    /** 查询商品类别列表 */
    getList() {
      this.loading = true;
      listCategory(this.queryParams).then((response) => {
        this.categoryList = this.handleTree(response.data, "id", "pid");
        this.loading = false;
      });
    },
    /** 转换商品类别数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
      };
    },
    /** 查询商品类别下拉树结构 */
    getTreeselect() {
      listCategory().then((response) => {
        this.categoryOptions = [];
        const data = { id: 0, name: "顶级节点", children: [] };
        data.children = this.handleTree(response.data, "id", "pid");
        this.categoryOptions.push(data);
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        createBy: null,
        createTime: null,
        modifyBy: null,
        modifyTime: null,
        descript: null,
        icon: "http://192.168.56.200:9000/ry-file/2022/02/05/b68e66b4-f1fc-4305-85bc-6b8c6fdb8aea.png",
        isDelete: null,
        name: null,
        pid: null,
        showIndex: null,
        sort: null,
        url: null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.reset();
      this.getTreeselect();
      if (row != null && row.id) {
        this.form.pid = row.id;
      } else {
        this.form.pid = 0;
      }
      this.open = true;
      this.title = "添加商品类别";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getTreeselect();
      if (row != null) {
        this.form.pid = row.id;
      }
      getCategory(row.id).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = "修改商品类别";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateCategory(this.form).then((response) => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCategory(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除商品类别编号为"' + row.id + '"的数据项？')
        .then(function () {
          return delCategory(row.id);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },
  },
};
</script>
<style scoped lang="scss">
.uploadpic {
  position: relative;
  display: inline-block;
  height: 120px;
}

.uploadpic:hover:after {
  content: "点击上传";
  position: absolute;
  left: 0;
  right: 0;
  top: 0;
  bottom: 0;
  color: #eee;
  background: rgba(0, 0, 0, 0.5);
  font-size: 30px;
  font-style: normal;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  cursor: pointer;
  line-height: 120px;
}
</style>